<template lang="pug">
  .checkout.head-page(v-if='isShow', ref="checkoutWrap")
    HeadBar(title="付款", @closeBar="isShow = false")
    Scroll.desc-wrap(v-if='!payFlag', :data="cartList")
      .inner
        van-cell(
          is-link,
          @click="changeAddress",
          v-if="getChangeAddress")
          .address
            .addr-info
              .title
                span.name {{getChangeAddress.name}} &nbsp;
                span.phone {{getChangeAddress.mobile}}
              .address-detail.omit2 {{getChangeAddress.province}}{{getChangeAddress.city}}{{getChangeAddress.address}}
            .choose 修改
        van-cell(v-if="!getChangeAddress", is-link, @click="changeAddress")
          .address
            .addr-info
              .title
                span.name 请先添加地址

        .product-list
          .item(v-for="(item, index) in getCartListItems", :key="index")
            .thumb
              img(:src="item.productimgs[0].thumburl")
            .info.pos-r
              .title.omit {{item.name}}
              .desc.pos-a
              .extra.pos-a.tar
                .price ￥ {{item.price}}
                .count {{item.num}}

        .total-money.tar
          span 共计 {{cartList.length}} 商品
          span 小计：
            strong.red ￥ {{Number(totalMoney).toFixed(2) }}

        .pay-method
          h3 付款方式
          van-radio-group(v-model="payment", @change="chagnePayment")
            van-cell-group
              van-cell(@click="payment = '3'")
                van-radio(name='3') 余额支付
              van-cell(@click="payment = '2'")
                van-radio(name='2') 微信支付
      .footbar-btn
        van-button.mt20(type="primary", bottom-action, size="large", @click="handleCheckout") 支付
    .content.tac(v-else)
        .pay-succ-icon
          i.iconfont.icon-roundcheck
        .pay-succ-info
          h2 支付完成
          p 您可以在
            a(href='', @click.stop.prevent='showOrderList') &nbsp; 我的订单 &nbsp;
            | 中查看该订单信息
          p 该窗口将在
            strong.red &nbsp;{{closeTime}}s&nbsp;
            | 后自动关闭
</template>

<script>
import Scroll from 'Comps/Scroll'
import headBarMixin  from '@/mixins/headBar'
import autoSwitchSceneMixin  from '@/mixins/switch-scene'
import { mapGetters } from 'vuex'
import { Toast } from 'vant'

let payBtn = true

export default {
  name: 'checkout',
  mixins: [headBarMixin, autoSwitchSceneMixin],
  data() {
    return {
      isShow: false,
      cartList: [],
      cartidStr: [],
      payment: '2',
      totalMoney: 0,
      chooseAddr: null,
      timer: null,
      closeTime: 10,
      payFlag: false
    }
  },
  mounted() {

    this.$nextTick(() => {
      // 从购物车页面过来结算
      this.getCheckoutInfo()
      // 获取选择的地址
      this.getChooseAddr()
    })


    // 支付成功
    this.paySuccess()
    // 支付失败
    this.payFailed()
  },
  computed: {
    ...mapGetters(['addressList', 'userBalance', 'userInfo']),
    getCartListItems() {
      return this.cartList
    },
    getAddress() {
      return this.addressList
    },
    getChangeAddress() {
      return this.chooseAddr
        ? this.chooseAddr
        : this.addressList
          ? this.addressList[0]
          : null
    }
  },
  methods: {
    getCheckoutInfo() {
      this.$vgo.on('checkout', (data) => {
        this.isShow = true
        this.payFlag = false
        this.cartList = []
        this.cartList = data.goods
        this.totalMoney = data.money

        if(!this.addressList) {
          this.getUserAddresses()
        }
        if(!this.userBalance) {
          this.$store.dispatch('getUserBalance', this.totalMoney)
        }

        const checkDom = this.$refs.checkoutWrap
        setTimeout(() => {
          if(checkDom) {
            checkDom.style.zIndex = '100'
          }
        }, 100)
      })
    },
    getChooseAddr() {
      this.$vgo.on('choose:address', data => {
        this.chooseAddr = data
      })
    },
    // 付款成功
    paySuccess() {
      this.$vgo.on('pay:success', data => {
        Toast.clear()
        if(!!data.data) {
          const openid = this.userInfo ? this.userInfo.wx_openid : ''
          window.location.href = data.data + '&iswx=true&pano_id='+ this.$route.params.panoId +'&openid=' + openid
        }
        else {
          this.$vgo.tip('支付成功', 'success')
          this.countDown()
          this.closeIframe()
        }
      })
    },
    payFailed() {
      this.$vgo.on('pay:failed', () => {
        //this.$vgo.tip('网络异常，支付失败！', 'error')
        this.closeIframe()
      })
    },
    // 显示地址选择列表
    changeAddress() {
      this.$vgo.emit('address:show')
    },
    // 获取用户收货地址
    getUserAddresses() {
      this.$store.dispatch('fetchUserAddress')
    },
    // 选择付款方式
    chagnePayment(val) {
      console.log(val)
    },
    // 支付创建订单
    handleCheckout() {
      if(!payBtn) return
      payBtn = false
      setTimeout(() => {
        payBtn = true
      }, 1000)

      if(!this.getChangeAddress) {
        Toast('请先添加收货地址')
        return
      }

      if (this.payment == 3) {
        // this.userBalance这个值为0，判断有点问题
        if((this.userBalance && this.userBalance == 0) && this.userBalance < this.totalMoney) {
          this.$vgo.tip('您的账户余额不足，请先充值！', 'warning')
          return
        }
      } else if (window.navigator.userAgent.toLowerCase().indexOf('miniprogram') != -1) {
        return this.$vgo.tip('暂未开通微信小程序支付，请在微信浏览器中体验！', 'warning')
      }

      const toast = Toast.loading({
        duration: 0,       // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        mask: true,
        loadingType: 'spinner',
        message: '创建订单中'
      })

      this.pay()

      // 不管是否付款成功购物车的商品都没有了，清除cookie
      const userId = this.userInfo ? this.userInfo.user_id : 0
      $VM.$AUTH.delCookie('cart|' + userId)
    },
    // 付款
    pay() {
      let cartidStr = []
      let isWx = this.payment == 2 ? true : false

      this.getCartListItems.map(item => {
        cartidStr.push(item.cartid)
      })
      cartidStr = "[" + cartidStr.join(',') + '' + "]"

      this.$store.dispatch('createOrder',
        {
          cartIds: cartidStr,
          address: this.getChangeAddress && this.getChangeAddress.addressid,
          money: this.totalMoney,
          payment: Number(this.payment),
          url: this.$route.path,
          iswx: isWx
        })
    },
    countDown() {
      this.timer = setTimeout(() => {
        this.closeTime--
        if(this.closeTime > 0) {
          this.countDown()
        } else {
          this.isShow = false
          this.closeTime = 10
          clearTimeout(this.timer)
          this.$refs.checkoutWrap.style.zIndex = '100'
        }
      }, 1000)
    },
    showOrderList() {
      this.$vgo.emit('order:usercenter')
      this.closeIframe()
    },
    closeIframe() {
      clearTimeout(this.timer)
      setTimeout(() => {
        Toast.clear()
        this.closeTime = 10
        this.isShow = false
        this.payFlag = false

        // 重新开启场景自动切换
        this.handleRestartAutoSwitchScene()
        this.$refs.checkoutWrap.style.zIndex = '100'
      }, 1000)
    }
  },
  components: {
    Scroll
  }
}
</script>

<style lang="stylus">
@import '../../../assets/styles/color.styl'
.checkout
  z-index: 101
  .desc-wrap
    display: flex
    justify-content: center
    align-items: center
    flex-direction: column
    overflow: hidden
    position: fixed
    top: 46px
    bottom: 0
    width: 100%
    .inner
      flex: 1
      top: 0
      width: 100%
      padding-bottom: 50px
      box-sizing: border-box
      position absolute
      .van-cell
        align-items: center
      .address
        display: flex
        padding: 0 10px
        .choose
          flex: 0 0 30px
          width: 30px
          line-height: 55px
        .addr-info
          flex: 1
          padding-left: 10px
          .title
            font-size: 15px
            line-height: 30px
            color: $black
          .address-detail
            font-size: 13px
            color: $black-light

      .item
        display: flex
        width: 100%
        margin-bottom: 10px
        padding: 10px
        background: $white-dark
        box-sizing: border-box
        .choose
          flex: 0 0 20px
          width: 20px
          line-height: 80px
          font-size: 0
          color: $success
        .thumb
          flex: 0 0 80px
          width: 60px
          padding: 0 10px
          img
            width: 100%
            height: 80px
        .info
          flex: 1
          max-width: 70%
          padding-right: 10px
          box-sizing: border-box
          .title
            width: 80%
            height: 30px
            line-height: 30px
            font-size: 14px
            font-weight: 700
            color: $black-dark
          .desc
            bottom: 0
            right: 0
            width: 100%
            height: 20px

            color: $black-light
          .extra
            right: 10px
            top: 4px
            font-weight: 700
            color: $black-light
      .total-money
        font-size: 14px
        padding: 20px
        color: $black-light
        span
          margin-left: 10px
        strong
          font-weight: 700
          font-size: 16px
          color: $danger
      .pay-method
        h3
          border-top: 1px solid #eee
          line-height: 40px
          padding-left: 10px
          font-size: 16px
          font-weight: bold
          color: $danger
  .footbar-btn
    position: fixed
    bottom: 0
    left: 0
    right: 0

  .pay-succ-icon
    padding: 30px 0
    i
      font-size: 120px
      color: $success
  .pay-succ-info
    h2
      font-size: 24px
      font-weight: 700
      color: $black
    p
      padding: 10px
      font-size: 16px
      color: $black-light
    a
      color: $blue
</style>
